﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAL;

namespace BLL
{
    
    public class KhachHangBUO:IBUO<tbl_Khach>
    {
        CSDLBanHangDataContext context = new CSDLBanHangDataContext();

        public bool Insert(tbl_Khach obj)
        {
            try
            {
                context.tbl_Khaches.InsertOnSubmit(obj);
                context.SubmitChanges();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool Delete(String id)
        {
            try
            {
                tbl_Khach obj = context.tbl_Khaches.Where(p => p.id_Khach.Equals(id)).FirstOrDefault();
                context.tbl_Khaches.DeleteOnSubmit(obj);
                context.SubmitChanges();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool Delete(tbl_Khach obj)
        {
            throw new NotImplementedException();
        }

        public List<tbl_Khach> GetAll()
        {
            return context.tbl_Khaches.OrderByDescending(p => p.id_Khach).ToList();
        }

        public tbl_Khach GetSingle(String id)
        {
            return context.tbl_Khaches.Where(p => p.id_Khach.Trim() == id.Trim()).FirstOrDefault();
        }

        public bool Update(String id, tbl_Khach obj)
        {
            tbl_Khach kh = context.tbl_Khaches.Where(p => p.id_Khach.Trim() == id.Trim()).FirstOrDefault();
            kh.TenKhach = obj.TenKhach;
            kh.DiaChi = obj.DiaChi;
            kh.SoDienThoai = obj.SoDienThoai;
            kh.Email = obj.Email;

            context.SubmitChanges();
            return true;
        }

        public List<tbl_Khach> searchByTenKhach(String name)
        {
            List<tbl_Khach> list = new List<tbl_Khach>();
            List<tbl_Khach> all = GetAll();

            if (all.Count > 0)
            {
                foreach (tbl_Khach a in all)
                {
                    if (a.TenKhach.ToLower().Trim().Contains(name.ToLower().Trim()))
                    {
                        list.Add(a);
                    }
                }
            }

            return list;
        }

        public List<tbl_Khach> searchByMaKhach(String ma)
        {
            return context.tbl_Khaches.Where(p => p.id_Khach.ToLower().Trim().Contains(ma.ToLower().Trim())).ToList<tbl_Khach>();
        }
    }
}
